package org.geometerplus.fbreader.formats.txt;

import com.iwanvi.common.GlobalConstants;
import com.chineseall.readerapi.entity.Chapter;
import com.chineseall.readerapi.utils.FileUtils;
import com.google.gson.Gson;
import com.iwanvi.common.network.ErrorMsgException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class ChapterParser {

	private List<Chapter> mChapters = new ArrayList<Chapter>();
	public static class LocalTxtDirectory
	{
		List<Chapter> mChapters = new ArrayList<Chapter>();
		public LocalTxtDirectory()
		{
			
		}
		public LocalTxtDirectory(List<Chapter> chapters)
		{
			mChapters = chapters;
		}
	}
	private String mBookId;
	public ChapterParser(String bookId)
	{
		mBookId = bookId;
	}
    public boolean hasDir()
    {
        File dir = new File(GlobalConstants.LOCAL_BOOK_PATH + "/" + mBookId + "/" + GlobalConstants.DIR_NAME);
        return dir.isFile() && dir.exists();
    }
	public void addChapter(String title, String Content)
	{
		Chapter chapter = new Chapter();
		chapter.setBookId("" + mBookId);
		
		title = title.replaceAll("\\s+", "");
		
		chapter.setName(title);
		chapter.setId("" + mChapters.size());
		saveChapter("" + mChapters.size(), Content);
		mChapters.add(chapter);
	}
    public List<Chapter> getAllChapters()
    {
        return mChapters;
    }
	
	private boolean saveChapter(String id, String content)
	{
		if (content != null) {
			String path = Chapter.getLocalTxtChapterFilePath("" + mBookId, id);
			File f;
			try {
				
				f = FileUtils.writeFromBuffer(path, content.toString().getBytes("utf-8"));
				if (f != null && f.exists()) {
					return true;

				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}
	public void saveDir()
	{

		String content = new Gson().toJson(new LocalTxtDirectory(mChapters)).toString();
		try
		{
			FileUtils.writeFromBuffer(GlobalConstants.LOCAL_BOOK_PATH + "/" + mBookId + "/" + GlobalConstants.DIR_NAME, content.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public int getChapterCount()
	{
		return mChapters.size();
	}


	public List<Chapter> loadDir()
	{
        File dirFile = new File(GlobalConstants.LOCAL_BOOK_PATH + "/" + mBookId + "/" + GlobalConstants.DIR_NAME);

        List<Chapter> ret = new ArrayList<Chapter>();
		try {
            String json = FileUtils.readFiletoString(dirFile.getPath(), "utf-8");

            JSONArray chapterArray = new JSONObject(json).getJSONArray("mChapters");
            if (chapterArray != null) {
                for (int m = 0; m < chapterArray.length(); m++) {
                    Chapter chapter = new Chapter();
                    JSONObject c = chapterArray.getJSONObject(m);
					chapter.setId(getString(c, "id"));
                    //针对于版本升级处理  ygzhang 4.1.2
                    if (c.has("n")){
                        chapter.setName(getString(c, "n"));
                    }else if (c.has("name")){
                        chapter.setName(getString(c, "n"));
                    }

                    chapter.setBookId("" + mBookId);
					ret.add(chapter);
				}

				chapterArray = null;
			}
		}
		catch(JSONException e)
		{
			e.printStackTrace();
            dirFile.delete();
		}
		catch (ErrorMsgException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}


	private static String getString(JSONObject o, String name)
			throws JSONException {
		if (!o.isNull(name))
			return o.getString(name);
		return "";
	}

}
